<?php
	header("Content-type:text/html;charset=UTF-8");
	class mysql{
		protected $con;

		/**
		 * 数据库连接
		 * @param [type] $config [description] 数据库配置信息
		 */
		public function __construct($config){
			$this->con=new mysqli($config['localhost'],$config['username'],$config['password'],$config['dbname']);
			if ($this->con->connect_error) {
				die("connection faild:".$this->con->connect_error);
			}
			$this->con->query('set names '.$config['charset']);
		}

		public function insert($table,$data){
			$sql="INSERT INTO ".$table."(";
			$sql.=implode(',', array_keys($data)).") VALUES('".implode("','", $data)."')";
			// echo $sql;die();
			if($this->con->query($sql)==true){

			}else{
				echo $this->con->error;
			}
		}


		public function select($table,$field="*",$where=false,$limit=false){
			$sql='select '.$field.' from '.$table;
			if($where)$sql.=' where '.$where;
			if($limit)$sql.=' limit '.$limit;
			if(!$res=$this->con->query($sql)) return $this->con->error;
			$data=array();
			while($arr=$res->fetch_assoc())
				array_push($data, $arr);
			$res->free();
			return $data;
		}

		public function update($table,$data,$where){
			$str='';
			foreach ($data as $k => $v) {
				$str.=$k."='".$v."',";
			}
			$str=substr($str,0,strlen($str)-1);
			$sql='update '.$table.' set '.$str.' where '.$where;
			$this->con->query($sql) or die($this->con->error);
		}

		public function del($table,$where){
			$sql="DELETE FROM ".$table." WHERE ".$where;
			return $this->con->query($sql) or die(0);
		}

		public function query($sql){
			if(!$res=$this->con->query($sql)) return $this->con->error;
			$data=array();
			while($arr=$res->fetch_assoc())
				array_push($data, $arr);
			$res->free();
			return $data;
		}


		public function __destruct(){
			$this->con->close();
		}
	}
?>
